<template>
  <view class="container" :class="{ dark: isDark }">
    <!-- 顶部标题栏 -->
    <view class="header">
      <text class="title">小车列表</text>
    </view>
    
    <!-- 搜索框 -->
    <view class="search-box">
      <uni-search-bar 
        v-model="searchText" 
        placeholder="搜索小车名称或IP" 
        radius="100"
        @confirm="handleSearch"
        @clear="clearSearch"
      />
    </view>
    
    <!-- 小车列表 -->
    <scroll-view 
      class="car-list" 
      scroll-y 
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <!-- 下拉刷新提示 -->
      <view class="refresh-tip" v-if="refreshing">
        <uni-load-more status="loading"></uni-load-more>
      </view>
      
      <!-- 空状态提示 -->
      <view class="empty-tip" v-if="filteredCars.length === 0">
        <image src="/static/images/empty-car.png" class="empty-image" />
        <text class="empty-text">{{ searchText ? '未找到匹配的小车' : '暂无小车数据' }}</text>
        <button class="refresh-btn" @click="fetchCarList">刷新数据</button>
      </view>
      
      <!-- 小车列表项 -->
      <view 
        class="car-item" 
        v-for="car in filteredCars" 
        :key="car.id"
        @click="navigateToControl(car)"
      >
        <image :src="car.avatar || '/static/images/car-default.png'" class="car-avatar" />
        <view class="car-info">
          <text class="car-name">{{ car.name }}</text>
          <text class="car-ip">{{ car.ip }}</text>
          <text class="car-status" :class="getStatusClass(car.status)">
            {{ getStatusText(car.status) }}
          </text>
        </view>
        <view class="car-actions">
          <button class="action-btn connect" @click.stop="connectCar(car)" v-if="!car.connected">
            连接
          </button>
          <button class="action-btn disconnect" @click.stop="disconnectCar(car)" v-else>
            断开
          </button>
        </view>
      </view>
      
      <!-- 加载更多提示 -->
      <uni-load-more 
        :status="loadingMore ? 'loading' : 'noMore'" 
        v-if="filteredCars.length > 0"
      />
    </scroll-view>
    
    <!-- 添加小车按钮 -->
    <view class="add-btn-container">
      <button class="add-btn" @click="showAddDialog">
        <uni-icons type="plus" size="24" color="#fff"></uni-icons>
        添加小车
      </button>
    </view>
    
    <!-- 添加/编辑小车对话框 -->
    <uni-popup ref="addDialog" type="dialog">
      <uni-popup-dialog 
        mode="input" 
        :title="isEditing ? '编辑小车' : '添加小车'"
        :placeholder="['小车名称', 'IP地址']"
        v-model="formData"
        @confirm="handleConfirm"
      />
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isDark: false,               // 是否暗黑模式
      searchText: '',              // 搜索文本
      refreshing: false,           // 是否正在刷新
      loadingMore: false,          // 是否正在加载更多
      isEditing: false,            // 是否编辑模式
      currentEditId: null,         // 当前编辑的小车ID
      formData: ['', ''],          // 表单数据 [name, ip]
      cars: [                      // 小车列表数据
        // 示例数据
        {
          id: 1,
          name: '探索者1号',
          ip: '192.168.1.101',
          status: 1,               // 0-离线 1-在线 2-忙碌
          connected: false,
          avatar: '/static/images/car1.png'
        },
        {
          id: 2,
          name: '巡逻者2号',
          ip: '192.168.1.102',
          status: 0,
          connected: false,
          avatar: '/static/images/car2.png'
        },
        {
          id: 3,
          name: '运输车3号',
          ip: '192.168.1.103',
          status: 2,
          connected: true,
          avatar: '/static/images/car3.png'
        }
      ]
    }
  },
  
  computed: {
    // 过滤后的小车列表
    filteredCars() {
      if (!this.searchText) return this.cars
      const search = this.searchText.toLowerCase()
      return this.cars.filter(car => 
        car.name.toLowerCase().includes(search) || 
        car.ip.includes(search)
    )
  },
  
  onShow() {
    // 检查暗黑模式设置
    this.checkDarkMode()
    // 加载小车列表
    this.fetchCarList()
  },
  
  methods: {
    // 检查暗黑模式设置
    checkDarkMode() {
      const dark = getApp().globalData.darkMode
      this.isDark = dark
      
      // 设置导航栏和tabbar样式
      if (dark) {
        uni.setTabBarStyle({
          backgroundColor: '#1e1e1e',
          borderStyle: 'black',
          color: '#999999',
          selectedColor: '#ffffff'
        })
        uni.setNavigationBarColor({
          frontColor: '#ffffff',
          backgroundColor: '#1e1e1e'
        })
      } else {
        uni.setTabBarStyle({
          backgroundColor: '#ffffff',
          borderStyle: 'black',
          color: '#7A7E83',
          selectedColor: '#fb7e29'
        })
        uni.setNavigationBarColor({
          frontColor: '#000000',
          backgroundColor: '#F8F8F8'
        })
      }
    },
    
    // 获取小车列表
    fetchCarList() {
      this.refreshing = true
      // 模拟API请求
      setTimeout(() => {
        // 这里应该是从服务器获取数据的逻辑
        // this.cars = await api.getCarList()
        this.refreshing = false
      }, 1000)
    },
    
    // 下拉刷新
    onRefresh() {
      this.fetchCarList()
    },
    
    // 处理搜索
    handleSearch() {
      // 搜索逻辑已在computed属性中实现
      console.log('搜索:', this.searchText)
    },
    
    // 清除搜索
    clearSearch() {
      this.searchText = ''
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '离线',
        1: '在线',
        2: '忙碌'
      }
      return statusMap[status] || '未知'
    },
    
    // 获取状态样式类
    getStatusClass(status) {
      const classMap = {
        0: 'offline',
        1: 'online',
        2: 'busy'
      }
      return classMap[status] || 'offline'
    },
    
    // 连接到小车
    connectCar(car) {
      uni.showLoading({ title: '连接中...' })
      // 模拟连接过程
      setTimeout(() => {
        car.connected = true
        uni.hideLoading()
        uni.showToast({
          title: `已连接到${car.name}`,
          icon: 'success'
        })
      }, 1500)
    },
    
    // 断开小车连接
    disconnectCar(car) {
      uni.showLoading({ title: '断开中...' })
      // 模拟断开过程
      setTimeout(() => {
        car.connected = false
        uni.hideLoading()
        uni.showToast({
          title: `已断开${car.name}`,
          icon: 'success'
        })
      }, 1000)
    },
    
    // 导航到控制页面
    navigateToControl(car) {
      if (!car.connected) {
        uni.showToast({
          title: '请先连接小车',
          icon: 'none'
        })
        return
      }
      
      uni.navigateTo({
        url: `/pages/control/control?carId=${car.id}&carName=${encodeURIComponent(car.name)}`
      })
    },
    
    // 显示添加对话框
    showAddDialog(editCar = null) {
      if (editCar) {
        // 编辑模式
        this.isEditing = true
        this.currentEditId = editCar.id
        this.formData = [editCar.name, editCar.ip]
      } else {
        // 添加模式
        this.isEditing = false
        this.currentEditId = null
        this.formData = ['', '']
      }
      this.$refs.addDialog.open()
    },
    
    // 处理确认添加/编辑
    handleConfirm([name, ip]) {
      if (!name || !ip) {
        uni.showToast({
          title: '请填写完整信息',
          icon: 'none'
        })
        return
      }
      
      // 验证IP地址格式
      if (!this.validateIP(ip)) {
        uni.showToast({
          title: '请输入有效的IP地址',
          icon: 'none'
        })
        return
      }
      
      if (this.isEditing) {
        // 更新小车信息
        const index = this.cars.findIndex(car => car.id === this.currentEditId)
        if (index !== -1) {
          this.cars[index].name = name
          this.cars[index].ip = ip
          uni.showToast({
            title: '修改成功',
            icon: 'success'
          })
        }
      } else {
        // 添加新小车
        const newCar = {
          id: Date.now(), // 使用时间戳作为临时ID
          name,
          ip,
          status: 0,
          connected: false,
          avatar: '/static/images/car-default.png'
        }
        this.cars.unshift(newCar)
        uni.showToast({
          title: '添加成功',
          icon: 'success'
        })
      }
      
      this.$refs.addDialog.close()
    },
    
    // 验证IP地址格式
    validateIP(ip) {
      const pattern = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
      return pattern.test(ip)
    },
    
    // 长按编辑小车
    handleLongPress(car) {
      uni.showActionSheet({
        itemList: ['编辑', '删除'],
        success: res => {
          if (res.tapIndex === 0) {
            this.showAddDialog(car)
          } else if (res.tapIndex === 1) {
            this.deleteCar(car)
          }
        }
      })
    },
    
    // 删除小车
    deleteCar(car) {
      uni.showModal({
        title: '确认删除',
        content: `确定要删除小车【${car.name}】吗？`,
        success: res => {
          if (res.confirm) {
            this.cars = this.cars.filter(item => item.id !== car.id)
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            })
          }
        }
      })
    }
  }
}}
</script>

<style lang="scss" scoped>
.container {
  background: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.header {
  background: linear-gradient(135deg, #ff6b35 0%, #f7931e 100%);
  padding: 60rpx 40rpx 30rpx;
  text-align: center;
  position: relative;
}

.title {
  color: white;
  font-size: 36rpx;
  font-weight: 600;
}

.search-box {
  padding: 20rpx 30rpx;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
}

.car-list {
  height: calc(100vh - 260rpx);
  padding: 0 30rpx;
}

.car-item {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  position: relative;
}

.car-avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  margin-right: 24rpx;
}

.car-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.car-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 8rpx;
}

.car-ip {
  font-size: 26rpx;
  color: #999;
  margin-bottom: 8rpx;
}

.car-status {
  font-size: 24rpx;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
  align-self: flex-start;
  
  &.online {
    background-color: #e8f5e9;
    color: #2e7d32;
  }
  
  &.offline {
    background-color: #ffebee;
    color: #c62828;
  }
  
  &.busy {
    background-color: #fff8e1;
    color: #f57f17;
  }
}

.car-actions {
  margin-left: 20rpx;
}

.action-btn {
  font-size: 26rpx;
  padding: 10rpx 24rpx;
  border-radius: 30rpx;
  margin: 0;
  
  &.connect {
    background-color: #4caf50;
    color: white;
  }
  
  &.disconnect {
    background-color: #f44336;
    color: white;
  }
}

.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 0;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
  opacity: 0.6;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 40rpx;
}

.refresh-btn {
  background-color: #ff6b35;
  color: white;
  font-size: 28rpx;
  padding: 16rpx 40rpx;
  border-radius: 40rpx;
}

.refresh-tip {
  padding: 20rpx 0;
  display: flex;
  justify-content: center;
}

.add-btn-container {
  position: fixed;
  bottom: 40rpx;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
}

.add-btn {
  background: linear-gradient(135deg, #ff6b35 0%, #f7931e 100%);
  color: white;
  font-size: 30rpx;
  padding: 20rpx 40rpx;
  border-radius: 50rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 4rpx 20rpx rgba(247, 147, 30, 0.3);
  
  &::after {
    border: none;
  }
}

/* 夜间模式 */
.dark {
  background: #121212;
  
  .header {
    background: linear-gradient(135deg, #333333 0%, #555555 100%);
  }
  
  .title {
    color: #eeeeee;
  }
  
  .search-box {
    background-color: #1e1e1e;
  }
  
  .car-item {
    background-color: #2a2a2a;
  }
  
  .car-name {
    color: #e0e0e0;
  }
  
  .car-ip {
    color: #757575;
  }
  
  .car-status {
    &.online {
      background-color: #1b5e20;
      color: #a5d6a7;
    }
    
    &.offline {
      background-color: #b71c1c;
      color: #ef9a9a;
    }
    
    &.busy {
      background-color: #e65100;
      color: #ffcc80;
    }
  }
  
  .empty-text {
    color: #757575;
  }
}
</style>